function showButton()
{
    $(this).fadeTo( 150, 1 );
}

function hideButton()
{
    $(this).fadeTo( 150, 0 );
}

function imageAlign( img )
{
    var divWidth  = $( '.slide_show' ).width();
    var divHeight = $( '.slide_show' ).height();
    
    var left = ( divWidth - img.width() ) / 2;
    var top  = ( divHeight - img.height() ) / 2;

    if ( ( img.width() ) == divWidth )
    {
        left = 0;
    }
    else if ( ( img.height() ) == divHeight )
    {
        top = 0;
    }

    img.css({
        'left' : left,
        'top'  : top
    });
}

function changeImage( navigation )
{
    var img        = $( '#ss_image' );
    var fileName   = img.attr( 'alt' );
    
    var param = '?current_img=' + fileName + '&navigation=' + navigation;
    
    $.get( '/php/ajax/slide_show_image.php' + param, function( responseText )
    {
        img.hide();
        if ( responseText == 'no images' )
        {
            img.attr( 'src', '../images/fb_form/no_images.jpg' );
            img.attr( 'alt', 'no_available' );
            clearInterval( g_interval );
        }
        else
        {
            img.attr( 'src', '../uploaded/' + responseText );
            img.attr( 'alt', responseText );            
        }
        setTimeout( function(){
            imageAlign( img );
            img.fadeIn( 300 );
        }, 100 )
    } );
}

function leafImage()
{
    clearInterval( g_interval );
    changeImage( this.id );
    g_interval = setInterval( function(){ changeImage( 'next' ) }, g_showTimeOut );
}

function startSlideShow()
{
    changeImage( 'next' );
    g_interval = setInterval( function(){ changeImage( 'next' ) }, g_showTimeOut );
}

var g_interval    = '';
var g_showTimeOut = 5000;

function initializeButtons()
{
    var leftButton = $('#prev');
    leftButton.hover( showButton, hideButton );
    leftButton.click( leafImage );
    leftButton.css( 'opacity', '0' );
    
    var rightButton = $('#next');
    rightButton.hover( showButton, hideButton );
    rightButton.click( leafImage );
    rightButton.css( 'opacity', '0' );
}

function isImagesAvailable()
{
    var img = $( '#ss_image' );
    $.get( '/php/ajax/slide_show_image.php', function( responseText )
    {
        if ( responseText == 'no images' )
        {
            img.hide();
            img.attr( 'src', '../images/fb_form/no_images.jpg' );
            img.attr( 'alt', 'no_available' );
            imageAlign( img );
            img.fadeIn( 300 );
        }
    } );
    return true;
}

function buildSlideShow()
{
    isImagesAvailable();
    var imageAltAttr = $( '#ss_image' ).attr( 'alt' );
    
    if ( imageAltAttr != 'no_available' )
    {
        initializeButtons();
        $('div').mousedown( function(){ return false;} );
        startSlideShow();
    }
}

$(document).ready( buildSlideShow );